<template>
	<view class="page">
		<view>
			<u-navbar leftText="返回" title="AI对话" bgColor="#f9e4e2">
				<view class="u-nav-slot njmdb" slot="left">
					<u-icon name="arrow-left" size="20" @click="navBack"></u-icon>
					<u-line direction="column" :hairline="false" length="16" margin="0 8px"></u-line>
					<u-icon name="list-dot" size="24" @click="showHistory"></u-icon>
				</view>
			</u-navbar>
		</view>
		<view class="page-content">
			<view class="dialog-detail" v-if="alReponse || answerList.length>0">
				<scroll-view :scroll-y="true" :scroll-top="scrollTop" style="height: calc(100vh - 280rpx);">
					<view id="scrollView" style="padding-bottom: 100rpx;box-sizing: border-box;">
						<block v-for="(item, index) in answerList" :key="index">
							<view class="answer-content " v-if="item.type == 'me'">
								<view class="answer-box answer-box1">
									<view class="answer answer1">{{ item.content }}</view>
								</view>
								<view class="headimg headimg1">
									<image
										:src="headimg?headimg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/icon/moren.png'">
									</image>
								</view>
							</view>
							<view class="answer-content" v-else>
								
								<view class="headimg">
									<image :src="localIconSrc('logo.png')"></image>
								</view>
								<view class="answer-box answer-box2">
									<view class="answer answer2">
										<view style="display: flex;align-items: center;"
											v-if="answerList.length==index+1 && item.content==''&&loading">
											<text>思考中</text>
											<view class="text">
												<view class="bar"></view>
												<view class="bar"></view>
												<view class="bar"></view>
											</view>
										</view>
										<!-- <view v-if="!loading">请按照提示操作后重试</view> -->
										<mp-html
											:content="marked(item.content)+(lightShow && answerList.length==index+1 ? `<div class='light-icon'></div>` : '')" />
										<view class="icon-title" v-if="!lightShow && item.content && !item.flag">
											<view class="tit">AI 生成内容仅供参考，不代表平台立场。</view>
											<view><u--text @click="copyContent(item.content)" size="26rpx" type="primary"
											text="复制"></u--text></view>
										</view>
										

									</view>
								</view>
							</view>
						</block>
					</view>
				</scroll-view>
			</view>
			<view v-if="answerList.length<=0">
				<view class="logo">
					<image :src="localIconSrc('logo.png')"></image>
					<view class="title">您好，我是爱云艺人工智能AI</view>
					<view class="describe">无形大脑，有行贡献，科技智慧，触手可及</view>
				</view>
				
				<view class="comment-box">
					<view class="comment-title"><text>我可以写文案、想点子、解答问题</text> <text class="t1"
							@click="changeDefault">换一换</text></view>
					<view class="loop-box">
						<view class="loop" @click="defaultDialog(index)" v-for="(item,index) in defaultList"
							:key="index">
							<!-- <view class="left">
								<image src="../../../static/logo.png"></image>
							</view> -->
							<view class="right">
								<view class="title">{{item.title}}</view>
								<view class="remark">{{item.content}}</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="input-box" :style="'bottom:'+bottomHeight+'px'">
				<view class="inp"><u--textarea :adjustPosition="false" @confirm="sendFun" :showConfirmBar="false"
						v-model="inputVal" placeholder="请输入内容" autoHeight :fixed="true"></u--textarea></view>
				<view class="icon" @click="sendFun">
					<u-button text="发送" color="#FFC9AA" :customStyle="sstype"></u-button>
					<!-- <image src="../../../static/image/send.png"></image> -->
				</view>
			</view>
			<div class="dialog-content"></div>
		</view>
		<u-popup :customStyle="customStyles" :show="show" @close="show=false" mode="left" :safeAreaInsetTop="true">
			<view class="pup-box">
				<view style="height: 44px;"></view>
				<view class="create-btn">
					<view class="btn" @click="newDialog">
						<u-button color="#FF6005" :plain="true" text="新建对话"></u-button>
					</view>
					<view style="height: 40rpx;width: 40rpx;">
						<image style="height: 100%;width: 100%;" @click="clearDialog" :src="localIconSrc('clear.png')"></image>
					</view>
					
				</view>
				<view class="history-box">
					<view @click="changeDialog(index)" class="item" v-for="(item,index) in historyList"
						:style="index==active?'background-color:#ffe2d2':''">{{item.detail[0].content}}</view>
					<view class="nodata" v-if="historyList.length<=0" style="margin-top: 200rpx;">
						<u-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png">
						</u-empty>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		marked
	} from "marked";
	import hljs from "highlight.js";
	import mpHtml from "mp-html/dist/uni-app/components/mp-html/mp-html";
	import "highlight.js/scss/atom-one-dark.scss";
	import {
		aiAnswer,
		createDialog,
		dialogList,
		pubTypeList,
		cleanDialog
	} from '@/api/index.js'
	export default {
		components: {
			mpHtml
		},
		data() {
			return {
				sstype: {
					color: "#FF6005",
					height: "70rpx",

				},
				headimg: uni.getStorageSync('portrait'),
				lightShow: false,
				marked: marked,
				answerList: [],
				show: false,
				active: 0,
				inputVal: '',
				customStyles: {
					'backgroundColor': 'transparent'
				},
				alReponse: '',
				chartNumber: 0,
				sessionId: '',
				defaultList: [],
				defaultLists: [],
				historyList: [],
				scrollTop: 0,
				bottomHeight: 0,
				loading: true,
			};
		},
		watch: {
			alReponse(newValue) {
				if (this.chartNumber == 0 || this.chartNumber != this.alReponse.length) {
					this.chartWhite()
					this.scrollToBottom()
				}
			}
		},
		onUnload() {
			uni.offKeyboardHeightChange(() => {
				console.log('键盘高度变化监听器已移除');
			});
		},
		onLoad() {
			// this.initHighLight()
			// this.getPubTypeList()

			uni.onKeyboardHeightChange((res) => {
				if (res.height > 0) {
					// 键盘弹起
					console.log('键盘弹起，高度:', res.height);
					this.bottomHeight = res.height
					// 可以在这里处理键盘弹起后的逻辑，比如调整布局
				} else {
					// 键盘收起
					console.log('键盘收起');
					this.bottomHeight = 0
					// 可以在这里处理键盘收起后的逻辑
				}
			});
		},
		onShow() {
			this.initHighLight()
			this.getPubTypeList()
		},
		onShareTimeline() {
			return {
				title: 'AI对话',
				// query: 'code=' + this.code
			}
		},
		onShareAppMessage() {
			return {
				title: 'AI对话',
				path: '/pages/ai-create/ai-dialog/ai-dialog'
			}
		},
		methods: {
			copyContent(text) {
				uni.setClipboardData({
					data: text
				})
			},
			//滚动到底部
			scrollToBottom() {
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('#scrollView').boundingClientRect();
					query.exec((res) => {
						if (res && res[0] && res[0].height) {

							this.scrollTop = res[0].height+50; // 设置滚动条到达底部
						}
					});
				});
			},
			clearDialog() {
				if (this.historyList.length <= 0) {
					uni.showToast({
						title: '暂无可清除数据',
						icon: 'none'
					})
					return
				}
				uni.showLoading({
					title: '请稍后...'
				})
				cleanDialog().then(res => {
					this.historyList = [];
					this.show = false;
					this.alReponse = '';
					this.answerList = []
					this.inputVal = '';
					this.chartNumber = 0
					uni.showToast({
						title: '操作成功',
						icon: 'none'
					})
				}).catch(err => {
					uni.hideLoading()
				})
			},
			showHistory() {
				this.getDialogList()
			},
			defaultDialog(index) {
				if (uni.getStorageSync('apiticket')) {
					uni.showLoading({
						title: '请稍后...'
					})
					
					createDialog().then(res => {
						console.log('dialogres', res)
						if(res.errcode && res.errcode != 200) {
							return
						} else {
							this.sessionId = res.session_id
								aiAnswer({
									content: this.defaultList[index].content,
									session_id: res.session_id
								}).then((res) => {
									if (res.errcode && res.errcode != 200) {
										uni.hideLoading()
										uni.showToast({
											title: res.errmsg,
											icon: 'none'
										})
									} else {
										let param = {
											type: 'me',
											content: this.defaultList[index].content
										}
										this.answerList.push(param)
										let params = {
											type: 'you',
											flag: false,
											content: ''
										}
										this.answerList.push(params)
										console.log(res)
										this.lightShow = true
										this.inputVal = ''
										this.connectWeb(res)
										uni.hideLoading()
									}
							
								})
						}
					})
				} else {
					uni.showModal({
						title: "提示",
						content: "请先登录",
						success(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: "/pages/login/index",
								})
							}
						},
					});
				}
			},
			changeDefault() {
				this.defaultList = this.getDialog(this.defaultLists, 5)
			},
			//随机获取默认对话
			getDialog(array, length) {
				// 创建一个数组，用于存放随机选择的元素
				const result = [];

				// 创建一个副本用于从中选择元素
				const arrayCopy = [...array];

				// 随机选择不重复的元素
				for (let i = 0; i < length; i++) {
					// 随机选择一个索引
					const randomIndex = Math.floor(Math.random() * arrayCopy.length);
					// 从副本数组中选择一个元素并添加到结果数组中
					result.push(arrayCopy[randomIndex]);
					// 从副本数组中删除已选择的元素以确保不重复
					arrayCopy.splice(randomIndex, 1);
				}

				return result;
			},
			//获取默认对话
			getPubTypeList() {
				uni.showLoading({
					title: '请稍后...'
				})
				pubTypeList().then(res => {
					console.log(res)
					this.defaultLists = res.ai_creation_example
					let str = this.getDialog(res.ai_creation_example, 5)
					this.defaultList = str
					uni.hideLoading()

				}).catch(err => {
					uni.hideLoading()
				})
			},
			//历史对话
			getDialogList() {
				uni.showLoading({
					title: '请稍后...'
				})
				dialogList().then(res => {
					this.historyList = res.history
					uni.hideLoading()
					this.show = true
				})
			},
			newDialog() {
				if (this.lightShow) {
					uni.showToast({
						title: '请等待对话完成',
						icon: 'none'
					})
					return
				}
				if (this.answerList.length == 1) {
					return
				}
				createDialog().then(res => {
					console.log(res)
					this.sessionId = res.session_id
					this.answerList = []
					let params = {
						type: 'you',
						content: ''
					}
					this.chartNumber = 0
					this.answerList.push(params)
					this.show = false
					this.alReponse = res.welcome_text
					this.chartWhite()
				})
			},
			navBack() {
				uni.navigateBack()
			},
			//获取回答地址
			anAnswerFun() {
				this.loading = true
				if (!this.sessionId) {
					createDialog().then(res => {
						console.log(res)
						this.sessionId = res.session_id
						aiAnswer({
							content: this.inputVal,
							session_id: res.session_id
						}).then((res) => {
							if (res.errcode && res.errcode != 200) {
								uni.showToast({
									title: res.errmsg,
									icon: 'none',
									duration: 5000
								})
								this.inputVal = ''
								this.lightShow = false
								this.loading = false
								this.answerList[this.answerList.length - 1].content = res.errmsg
								this.answerList[this.answerList.length - 1].flag = true
							} else {
								console.log(res)
								this.lightShow = true
								this.inputVal = ''
								this.loading = false
								this.connectWeb(res)
							}
						})
					})
				} else {
					aiAnswer({
						content: this.inputVal,
						session_id: this.sessionId
					}).then((res) => {
						if (res.errcode && res.errcode != 200) {
							uni.hideLoading()
							uni.showToast({
								title: res.errmsg,
								icon: 'none',
								duration: 5000
							})
							this.inputVal = ''
							this.lightShow = false
							this.loading = false
							this.answerList[this.answerList.length - 1].content = res.errmsg
							this.answerList[this.answerList.length - 1].flag = true
						} else {
							console.log(res)
							this.lightShow = true
							this.inputVal = ''
							this.loading = false
							this.connectWeb(res)
						}
					})
				}
			},
			chartWhite() {
				if (this.chartNumber < this.alReponse.length) {
					let index = this.answerList.length - 1
					this.answerList[index].content += this.alReponse.charAt(this.chartNumber)
					this.chartNumber++
					setTimeout(this.chartWhite, 100) //控制打字速度
				}
			},
			connectWeb(res) {
				console.log(res)
				const webs = uni.connectSocket({
					url: 'wss://' + res.domain + '/chat/?uid=' + res.uid + '&session_id=' + res.session_id +
						'&openid=' + res.openid,
					header: {
						'content-type': 'application/json'
					},
					success: (res) => {
						console.log(res)
					},
					fail: (err) => {
						console.log(err)
					}
				})
				webs.onOpen((e) => {
					uni.hideLoading()
					console.log('open', e)
				})
				webs.onError((e) => {
					uni.hideLoading()
					console.log('err', e)
				})
				webs.onMessage((e) => {
					if (e.data == 'Done') {
						this.lightShow = false
						webs.close()
						return
					} else {
						this.alReponse += e.data
					}
				})
				webs.onClose((e) => {
					console.log('close', e)
				})
			},
			changeDialog(index) {
				this.chartNumber = 0
				this.alReponse = ''
				this.answerList = []
				this.active = index
				let arr = this.historyList[index]
				let crr = []
				this.sessionId = arr.session_id
				arr.detail.forEach(item => {
					let param = {
						type: 'me',
						content: item.content
					}
					this.answerList.push(param)
					let params = {
						type: 'you',
						content: item.response.replace('Done', '')
					}
					this.answerList.push(params)
				})
				this.show = false
			},
			sendFun() {
				if (uni.getStorageSync('apiticket')) {
					if (this.inputVal != '') {
						let param = {
							type: 'me',
							content: this.inputVal
						}
						this.answerList.push(param)
						let params = {
							type: 'you',
							content: ''
						}
						this.answerList.push(params)
						this.anAnswerFun()
					} else {
						uni.showToast({
							title: '您还没有输入内容哦！',
							icon: 'none'
						})
					}
				} else {
					uni.showModal({
						title: "提示",
						content: "请先登录",
						success(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: "/pages/login/index",
								})
							}
						},
					});
				}
				if (this.lightShow) {
					uni.showToast({
						title: '请等待对话完成',
						icon: 'none'
					})
					return
				}
			},
			initHighLight() {
				hljs.configure({
					useBR: true,
					tabReplace: " ",
				});
				marked.setOptions({
					renderer: new marked.Renderer(),
					gfm: true,
					tables: true,
					breaks: false,
					pedantic: false,
					highlight: function(code, lang) {
						if (lang && hljs.getLanguage(lang)) {
							return hljs.highlight(lang, code, true).value;
						} else {
							return hljs.highlightAuto(code).value;
						}
					},
				});
			},
		},

	}
</script>
<style>
	@keyframes cursor-blink {

		0%,
		50% {
			opacity: 1;
			/* 光标可见 */
		}

		51%,
		100% {
			opacity: 0;
			/* 光标不可见 */
		}
	}

	.light-icon {
		width: 2px;
		height: 10px;
		background-color: skyblue;
		animation: cursor-blink 1s infinite step-end;
		/* 光标闪烁动画 */
	}
</style>
<style lang="scss" scoped>
	.icon-title {
		
		margin-top: 20rpx;
		.tit{
			font-size: 24rpx;
			color: #acacac;
		}

	}

	@keyframes bounce {

		0%,
		100% {
			transform: translateY(6rpx);
		}

		50% {
			transform: translateY(-6rpx);
		}
	}

	.text {
		font-size: 32rpx;
		font-weight: 600;
		display: flex;
		height: 24rpx;

		.bar {
			animation: bounce 1s infinite;
			background: linear-gradient(to top, #6F31F4, #FF6005);
			height: 10rpx;
			width: 10rpx;
			margin-left: 6rpx;
		}

		.bar:nth-child(1) {
			animation-delay: 0s;
		}

		.bar:nth-child(2) {
			animation-delay: 0.1s;
		}

		.bar:nth-child(3) {
			animation-delay: 0.2s;
		}
	}

	.page {
		background: linear-gradient(to bottom, #f9e4e2, #f2eaf8);
		min-height: 100vh;
	}

	.page-content {
		padding-top: calc(var(--status-bar-height) + 100rpx);

		.dialog-detail {
			width: 100%;
			padding: 20rpx 20rpx;
			box-sizing: border-box;

			.answer-content {
				width: 100%;
				// width: 500rpx;
				display: flex;
				margin-top: 20rpx;

				.headimg1 {
					float: right;
				}

				.headimg {
					width: 60rpx;
					height: 60rpx;
					border-radius: 50%;
					// background-color: #f3f3f3;

					image {
						height: 100%;
						width: 100%;
						border-radius: 50%;
					}
				}

				.answer-box1 {
					flex-direction: row-reverse;
					margin-right: 20rpx;
				}

				.answer-box2 {
					margin-left: 20rpx;
				}

				.answer-box {
					display: flex;
					flex: 1;

					.answer1 {
						background-color: #F6DED0;
					}

					.answer2 {
						background-color: #ffffff;
					}

					.answer {
						padding: 10rpx 20rpx;
						box-sizing: border-box;
						border-radius: 16rpx;
						max-width: 550rpx;
						overflow-x: scroll;
						line-height: 60rpx;
					}
				}
			}
		}

		.logo {
			height: 300rpx;
			width: 300rpx;
			margin: auto;
			position: relative;

			image {
				height: 220rpx;
				width: 220rpx;
				margin-left: 40rpx;
				margin-top: 30rpx;
			}

			.title {
				white-space: nowrap;
				text-align: center;
				position: absolute;
				bottom: -12rpx;
				left: 50%;
				transform: translateX(-50%);
				// background-color: #fff;
				padding: 4px 6px;
				border-radius: 10rpx;
				font-size: 32rpx;
				font-weight: bold;

			}
			
			.describe {
				white-space: nowrap;
				position: absolute;
				bottom: -70rpx;
				left: 50%;
				transform: translateX(-50%);
				font-size: 28rpx;
			}
		}

		.comment-box {
			background-color: #fff;
			width: 80%;
			margin: auto;
			margin-top: 100rpx;
			margin-bottom: 150rpx;
			padding: 40rpx 40rpx;
			box-sizing: border-box;
			border-radius: 16rpx;

			.loop-box {
				.loop {
					display: flex;
					align-items: center;
					margin-top: 50rpx;

					.left {
						width: 80rpx;
						height: 80rpx;

						image {
							width: 100%;
							height: 100%;
						}
					}

					.right {
						margin-left: 40rpx;

						.title {
							font-size: 32rpx;
							font-weight: 600;
							width: 400rpx;
							text-overflow: ellipsis;
							white-space: nowrap;
							overflow: hidden;
							color: #333;
						}

						.remark {
							font-size: 24rpx;
							color: #a8a8a8;
							width: 400rpx;
							text-overflow: ellipsis;
							white-space: nowrap;
							overflow: hidden;
							margin-top: 10rpx;
						}
					}
				}
			}

			.comment-title {
				width: 100%;
				display: flex;
				justify-content: space-between;
				font-size: 28rpx;

				.t1 {
					color: #31adff;
					font-size: 28rpx;
				}
			}
		}

		.input-box {
			background-color: #fff;
			display: flex;
			width: 100%;
			position: fixed;
			left: 50%;
			transform: translateX(-50%);
			padding: 20rpx 30rpx;
			box-sizing: border-box;
			align-items: center;

			.inp {
				max-height: 160rpx;
				overflow-y: scroll;
				width: calc(100% - 160rpx);
			}

			.icon {
				// background-color: #31adff;
				// height: 70rpx;
				width: 70rpx;
				border-radius: 50%;
				margin-left: 20rpx;
				flex: 1;
				// image {
				// 	margin-left: 14rpx;
				// 	margin-top: 14rpx;
				// 	height: 60%;
				// 	width: 60%;

				// }
			}
		}
	}

	.pup-box {
		width: 400rpx;

		.create-btn {
			width: 100%;
			height: 100rpx;
			background-color: #fff;
			// border: 1px solid red;

			padding: 20rpx 20rpx 0 20rpx;
			box-sizing: border-box;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.btn {
				// height: 60rpx;
				width: 250rpx;
			}

			image {
				width: 40rpx;
				height: 40rpx;
			}
		}

		.history-box {
			height: calc(100vh - 186rpx);
			overflow-y: scroll;
			padding: 60rpx 0;
			padding-bottom: 100rpx;
			box-sizing: border-box;
			background-color: #fff;

			.item {
				height: 80rpx;
				line-height: 80rpx;
				padding: 0 20rpx;
				box-sizing: border-box;
				white-space: nowrap;
				text-overflow: ellipsis;
				overflow: hidden;
				font-size: 28rpx;
			}
		}
	}

	.njmdb {
		display: flex;
		align-items: center;
	}
</style>